# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/2/19
# python-version    : Python 3.7.0
# description       : 文章操作相关接口


from flask import Flask, jsonify, request
from com.articles.microapp.service.articles_service import ArticleService
from com.articles.microapp.service.remarks_service import RemarkService
from com.articles.microapp.utils.logger_utils import Logger
from com.articles.microapp.utils.constants import CommonConstants
from com.articles.microapp.config.config import CONFIG


class ArticleController(object):
    consts = CommonConstants()
    config = CONFIG.config()

    logger = Logger()

    articles_service = ArticleService()
    remarks_service = RemarkService()

    def __init__(self, app=Flask(__name__)):
        app.add_url_rule("/getArticles", view_func=self.get_articles, methods=['GET'])
        app.add_url_rule("/getArticle", view_func=self.get_article, methods=['GET'])
        app.add_url_rule("/getBanners", view_func=self.get_banner, methods=['GET'])

    def get_articles(self):
        args1 = request.args.get('pageNo')
        page_no = 1 if not args1 or int(args1) < 1 else int(args1)
        page_size = 0 if not request.args.get('pageSize') else int(request.args.get('pageSize'))
        if page_size != 0:
            start = (page_no - 1) * page_size
            articles = self.articles_service.query_articles(page=[start, page_size])
        else:
            articles = self.articles_service.query_articles()
        return jsonify(articles)

    def get_banner(self):
        cnt = self.consts.DEFAULT_PAGE_SIZE
        if request.args.get('cnt'):
            cnt = int(request.args.get('cnt'))
        banner = self.articles_service.query_banner(page=[self.consts.DEFAULT_PAGE_NO, cnt])
        return jsonify(banner)

    def get_article(self):
        article_id = request.args.get('articleId')
        article = self.articles_service.query_article(article_id)
        user_id = '28045612534'
        article.isLocked = self.remarks_service.is_locked(article.articleId, user_id)
        return jsonify(article.__dict__)
